﻿using Newtonsoft.Json.Linq;
using Sharp.WeShare.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sharp.WeShare.MP.UserManager.Entity;

namespace Sharp.WeShare.MP.UserManager
{
    public class UserApi
    {
        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static TagRes CreateTag(string accessToken, string name)
        {
            var url =
       string.Format("https://api.weixin.qq.com/cgi-bin/tags/create?access_token={0}", accessToken);
            var obj = new { tag = new { name = name } };
            var Jobj = Utils.PostResult<JObject>(obj, url);
            JToken errcode = null;
            errcode = Jobj.GetValue("errcode");
            var ret = new TagRes();
            if (errcode == null)//判断是否存在错误返回码。如果不存在，则说明标签创建成功
            {
                ret.id = Jobj["tag"]["id"].Value<int>();
                ret.name = Jobj["tag"]["name"].Value<string>();
            }
            else
            {
                ret.errcode = errcode.Value<int>();
                ret.errmsg = Jobj.Value<string>("errmsg");
            }
            return ret;
        }
        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static TagsRes GetTags(string accessToken)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/get?access_token={0}", accessToken);
            return Utils.GetResult<TagsRes>(url);
        }
        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static BaseRes UpdateTag(string accessToken, int id, string name)
        {
            var url =
             string.Format("https://api.weixin.qq.com/cgi-bin/tags/update?access_token={0}", accessToken);
            var obj = new { tag = new { id = id, name = name } };
            return Utils.PostResult<BaseRes>(obj, url);
        }
        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static BaseRes DeleteTag(string accessToken, int id)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={0}", accessToken);
            var obj = new { tag = new { id = id } };
            return Utils.PostResult<BaseRes>(obj, url);
        }
        /// <summary>
        /// 获取标签下的用户列表
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="id"></param>
        /// <param name="nextOpenid"></param>
        /// <returns></returns>
        public static TagUsers GetTagUsers(string accessToken, int id, string nextOpenid = "")
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={0}", accessToken);
            var obj = new { tagid = id, next_openid = nextOpenid };
            var jobj = Utils.PostResult<JObject>(obj, url);
            var tagusers = new TagUsers();
            var errcode = jobj.GetValue("errcode");
            if (errcode == null)
            {
                tagusers.count = jobj.Value<int>("count");
                if (tagusers.count > 0)
                {
                    tagusers.next_openid = jobj.Value<string>("next_openid");
                    tagusers.openid = jobj["data"]["openid"].Select(r => r.Value<string>()).ToList();
                }
            }
            else
            {
                tagusers.errcode = errcode.Value<int>();
                tagusers.errmsg = jobj.Value<string>("errmsg");
            }
            return tagusers;
        }

        /// <summary>
        /// 批量为用户打标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openid_list"></param>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public static BaseRes BatchTagging(string accessToken, List<string> openid_list, int tagid)
        {
            var url =
            string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={0}", accessToken);
            var obj = new
            {
                openid_list = openid_list,
                tagid = tagid
            };
            return Utils.PostResult<BaseRes>(obj, url);
        }
        /// <summary>
        /// 批量为用户取消标签
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openid_list"></param>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public static BaseRes BatchUnTagging(string accessToken, List<string> openid_list, int tagid)
        {
            var url =
            string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={0}", accessToken);
            var obj = new
            {
                openid_list = openid_list,
                tagid = tagid
            };
            return Utils.PostResult<BaseRes>(obj, url);
        }
        /// <summary>
        /// 获取用户身上的标签列表
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static TagIds GetTagIdList(string accessToken, string openid)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={0}", accessToken);
            var obj = new { openid = openid };
            return Utils.PostResult<TagIds>(obj, url);
        }
        /// <summary>
        /// 更新用户备注
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openid"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public static BaseRes UpdateRemark(string accessToken, string openid, string remark)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token={0}", accessToken);
            var obj = new { openid = openid, remark = remark };
            return Utils.PostResult<BaseRes>(obj,url);
        }
        /// <summary>
        /// 获取用户基本信息（包括UnionID机制）
        /// </summary>
        /// <param name="accessToken">调用接口凭证</param>
        /// <param name="openid">普通用户的标识，对当前公众号唯一</param>
        /// <param name="lang">返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语</param>
        /// <returns></returns>
        public static UserInfo GetUserInfo(string accessToken, string openid,string lang= "zh_CN")
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang={2}",accessToken,openid,lang);
            return Utils.GetResult<UserInfo>(url);
        }
        /// <summary>
        /// 批量获取用户基本信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openids"></param>
        /// <returns></returns>
        public static BatchGetInfoRes BatchGetInfo(string accessToken, List<Openid> openids)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={0}",accessToken);
            return Utils.PostResult<BatchGetInfoRes>(new { user_list =openids}, url);
        }
        /// <summary>
        /// 获取关注用户的openid列表
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="nextOpenid"></param>
        /// <returns></returns>
        public static UserOpenIdRes GetUserList(string accessToken, string nextOpenid = "")
        {
            var url =
           string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}", accessToken, nextOpenid);
            var retdata = Utils.GetResult<UserOpenIdRes>(url);
            //判断调用是否成功。当调用成功，且总关注人数大于10 000,本次获取到的用户数量等于10 000时，则说明有尚未获取到的用户，此时递归调用，添加到列表
            if (retdata.errcode == 0 && retdata.total > 10000 && retdata.count == 10000)
            {
                retdata.data.openid.AddRange(GetUserList(accessToken, retdata.next_openid).data.openid);
            }
            return retdata;
        }
        /// <summary>
        /// 获取黑名单列表
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public static UserOpenIdRes GetBlackList(string accessToken,string openId)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={0}",accessToken);
            var data = new {begin_openid = openId};
            return Utils.PostResult<UserOpenIdRes>(data, url);
        }
        /// <summary>
        /// 批量添加进黑名单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openIds"></param>
        /// <returns></returns>
        public static BaseRes BatchBlackList(string accessToken, List<string> openIds)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={0}",accessToken);
            var data = new { openid_list =openIds};

            return Utils.PostResult<BaseRes>(data, url);
        }
        /// <summary>
        /// 批量取消黑名单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openIds"></param>
        /// <returns></returns>
        public static BaseRes BatchUnBlackList(string accessToken, List<string> openIds)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token={0}", accessToken);
            var data = new { openid_list = openIds };

            return Utils.PostResult<BaseRes>(data, url);
        }
    }
}
